//
//  HMComposeViewController.swift
//  Weibo
//
//  Created by fuyu on 2017/7/31.
//  Copyright © 2017年 itteacher. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

//  发微博视图控制器
class HMComposeViewController: UIViewController {
    //MARK: -- 懒加载
    private lazy var titleLabel: UILabel = {
        
       let label = UILabel(fontSize: 17, textColor: UIColor.darkGray)
        if let name = HMUserAccountViewModel.sharedViewModel.userAccount?.name {
            
            let title = "发微博\n" + name
            //  把字符串转成富文本
            let attributedStr: NSMutableAttributedString = NSMutableAttributedString(string: title)
            //  获取名字的范围
            let nameRange = (title as NSString).range(of: name)
            //  给指定范围添加对应的富文本属性
            attributedStr.addAttributes([NSForegroundColorAttributeName : UIColor.brown,NSFontAttributeName:UIFont.systemFont(ofSize: 12)], range: nameRange)
            //  设置富文本
            label.attributedText = attributedStr
        }else {
            
            label.text  = "发微博"
        }
        
        label.numberOfLines = 0
        label.textAlignment = .center
        label.sizeToFit()
        return label
    }()
    
    //发微博按钮
    private lazy var sendButtton: UIButton = {
        let button = UIButton()
        
        //添加点击事件
        button.addTarget(self, action: #selector(sendButtonAction), for: .touchUpInside)
        //设置不同状态下按钮的图片
        button.setBackgroundImage(UIImage(named: "common_button_orange"), for: .normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), for: .highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_disable"), for: .disabled)
        //设置文字
        button.setTitle("发送", for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        button.setTitleColor(UIColor.white, for: .normal)
        button.setTitleColor(UIColor.gray, for: .disabled)
        //大小
        button.size = CGSize(width: 45, height: 35)
        return button
        
    }()
    
    //textView
    fileprivate lazy var textView: HMTextView = {
        let textView = HMTextView()
        //  设置是否显示纠错视图
        //        textView.autocorrectionType = .no
        //设置代理
        textView.delegate = self
        textView.placeHolder = "挖掘机技术哪家强挖掘机技术哪家强挖掘机技术哪家强"
        textView.font = UIFont.systemFont(ofSize: 14)
        //  垂直方向设置弹簧效果
        textView.font = UIFont.systemFont(ofSize: 14)
        return textView
    }()
    
    //配图
    fileprivate lazy var pictureView: HMComposePictureView = {
        let collectionView = HMComposePictureView()
        collectionView.backgroundColor = self.textView.backgroundColor
        return collectionView
    }()

    //toolbar
    fileprivate lazy var toolBar: HMComposeToolbar = HMComposeToolbar()
    
    //表情键盘
    fileprivate lazy var emoticonKeyBoard: HMEmoticonKeyBoard = {
        let keyBoard = HMEmoticonKeyBoard(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: ScreenWidth, height: 216)))
        return keyBoard
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        setupUI()
    }
    
    private func setupUI() {
        //  监听键盘frame的改变
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardFrameChange), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
        
     setupNavUI()
        view.addSubview(textView)
        view.addSubview(toolBar)
        textView.addSubview(pictureView)
        textView.snp.makeConstraints { (make) in
            make.top.leading.trailing.equalTo(view)
            make.bottom.equalTo(toolBar.snp.top)
        }
        
        pictureView.snp.makeConstraints { (make) in
            make.top.equalTo(textView).offset(100)
            make.centerX.equalTo(textView)
            make.width.equalTo(textView).offset(-10)
            make.height.equalTo(textView.snp.width).offset(-10)
        }
        toolBar.snp.makeConstraints { (make) in
            make.bottom.equalTo(view)
            make.leading.trailing.equalTo(textView)
            make.height.equalTo(35)
        }
        //  设置闭包
        toolBar.toolBarButtonClosure = { [unowned self] (type: HMComposeToolbarButtonType) in
            switch type {
            case .picture:
                print("图片")
                self.clickPictureButtonAction()
            case .mention:
                print("@")
            case .trend:
                print("#")
            case .emoticon:
                print("表情")
                self.clickEmoticonButtonAction()
            case .add:
                print("加号")
            }
        }
        //  设置点击加号图片的闭包
        pictureView.clickAddClosure = { [unowned self] in
            self.clickPictureButtonAction()
        }
        
    }
    
    
    private func setupNavUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelAction))
        //自定义titleView
        navigationItem.titleView = titleLabel
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButtton)
        
        //默认不可用
        navigationItem.rightBarButtonItem?.isEnabled = false
    }
    
    //MARK: -- 点击取消按钮的事件处理
    @objc private func cancelAction() {
        //失去第一响应者
        textView.resignFirstResponder()
        
        dismiss(animated: true, completion: nil)
        
    }
    
    //  MARK: --    发送按钮点击事件处理
    @objc private func sendButtonAction() {
        
        //获取令牌
        let token = HMUserAccountViewModel.sharedViewModel.accessToken!
        //获取内容
        let text = textView.text!
        if pictureView.images.count > 0 {
            let image = pictureView.images.first!
            //  图片微博
            HMNetworkTools.sharedTools.sendWeibo(access_token: token, status: text, pic: image, callBack: { (response, error) in
                if error != nil {
                    print("error: \(error!)")
                    SVProgressHUD.showError(withStatus: "发送失败")
                    return
                }
                SVProgressHUD.showSuccess(withStatus: "发送成功")
            })
        } else {
            //  文字微博
            HMNetworkTools.sharedTools.sendWeibo(access_token: token, status: text) { (response, error) in
                if error != nil {
                    print("error: \(error!)")
                    SVProgressHUD.showError(withStatus: "发送失败")
                    return
                }
                SVProgressHUD.showSuccess(withStatus: "发送成功")
            }
        }
        
        
    }

    //  MARK: --    监听键盘frame的改变
    @objc private func keyboardFrameChange(noti: NSNotification) {
        
        let userInfo = noti.userInfo!
        //  获取键盘的frame
        let keyboardFrame = userInfo[UIKeyboardFrameEndUserInfoKey] as! CGRect
        
        //更新约束
        toolBar.snp.updateConstraints { (make) in
            make.bottom.equalTo(view).offset(keyboardFrame.origin.y-ScreenHeight)
        }
        //  执行约束动画
        UIView.animate(withDuration: 0.25) { 
            self.view.layoutIfNeeded()
        }
        
    }
    //  移除通知
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
}

//  MARK: --toolbar按钮点击的逻辑处理
extension HMComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    //  点击表情按钮的逻辑处理
    func clickEmoticonButtonAction() {
        if textView.inputView == nil {
            //  设置输入视图， 由系统键盘进入表情键盘
            textView.inputView = emoticonKeyBoard
            toolBar.switchButtonIcon(isEmoticon: true)
        } else {
            //  设置输入视图,  由表情键盘进入系统键盘
            textView.inputView = nil
            toolBar.switchButtonIcon(isEmoticon: false)
        }
        
        //  成为第一响应者
        textView.becomeFirstResponder()
        //  重新加载输入视图
        textView.reloadInputViews()
        
    }

    //  点击图片按钮的逻辑处理
    func clickPictureButtonAction() {
        //  创建图片浏览器
        let imagePicCtr = UIImagePickerController()
        //设置代理
        imagePicCtr.delegate = self
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            //  设置来源类型, 真机使用相机
            imagePicCtr.sourceType = .camera
        }else {
            
            //  设置来源类型, 模拟器使用图库
            imagePicCtr.sourceType = .photoLibrary
        }
        //  图片允许编辑
        //imagePicCtr.allowsEditing = true
        
        self.present(imagePicCtr, animated: true, completion: nil)
        
    }
    //  MARK: --UIImagePickerControllerDelegate
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        //  UIImagePickerControllerEditedImage 获取编辑后图片
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        //  压缩后的图片
        let currentImage = scaleImage(scaleWidth: 100, image: image)
        //  显示配图图片
        pictureView.addImage(image: currentImage)
        picker.dismiss(animated: true, completion: nil)
    }
    
    //  等比压缩图片
    func scaleImage(scaleWidth: CGFloat, image: UIImage) -> UIImage {
        //  计算压缩后的高度
        let scaleHeight = scaleWidth / image.size.width * image.size.height
        //  压缩后的大小
        let scaleSize = CGSize(width: scaleWidth, height: scaleHeight)
        //  开启图片上下文
        UIGraphicsBeginImageContext(scaleSize)
        //  渲染的区域
        let rect = CGRect(origin: CGPoint.zero, size: scaleSize)
        //  把图片渲染到指定区域
        image.draw(in: rect)
        //  通过图片上下文获取当前图片
        let currentImage = UIGraphicsGetImageFromCurrentImageContext()
        //  结束图片上下文
        UIGraphicsEndImageContext()
        return currentImage!
    }
    
}

//  MARK: --UITextViewDelegate
extension HMComposeViewController: UITextViewDelegate {
        func textViewDidChange(_ textView: UITextView) {
            
            //根据文本框是否有内容判断是否可用
            navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
        }
        
        //  将要拖拽
        func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
            //结束编辑失去第一响应者
            self.view.endEditing(true)
        }
        
    }

